from django.http import HttpResponse
# Create your views here.
from django_redis import get_redis_connection
from rest_framework.views import APIView
from . import serializers
from meiduo_mall.libs.captcha.captcha import captcha
from . import constants
import random
from meiduo_mall.libs.yuntongxun.sms import CCP
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
from celery_tasks.sms import tasks as sms_tasks
from celery_tasks.sms.tasks import send_sms_code


#设置短信验证码
class SMSCodeView(GenericAPIView):
    #指定序列化器
    serializer_class = serializers.ImageCodeCheckSerializer

    def get(self,request,mobile):
        """接受参数mobile、image_code_id,text，校验参数image_code_id,text
        ，对比用户发来的text与存储的text是否一样"""
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        #生成随机短信验证码
        sms_code = "%06d" % random.randint(0,999999)
        print(sms_code)


        # 发送短信验证码
        sms_code_expires = str(constants.SMS_CODE_REDIS_EXPIRES // 60)
        sms_tasks.send_sms_code.delay(mobile, sms_code, sms_code_expires)
        #异步发送短信
        # send_sms_code.delay(mobile, sms_code)

        # CCP().send_template_sms(mobile,[sms_code,constants.SMS_CODE_REDIS_EXPIRES//60],1)



        #存储短信验证码
        redis_conn = get_redis_connection('verify_codes')
        # redis_conn.setex("sms_%s" % mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
        # #判断是否在60s内重复发送短信
        # redis_conn.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        pl = redis_conn.pipeline()
        # redis_conn = get_redis_connection('verify_codes')
        pl.setex("sms_%s" % mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
        #判断是否在60s内重复发送短信
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()
        #响应短信验证码
        return Response({'message':'OK'})


class ImageCodeView(APIView):
    """
    图片验证码
    """

    def get(self, request,image_code_id):
        """获取图片验证码"""
        #生成图片验证码
        text, image = captcha.generate_captcha()
        print(text)
        #存储图片验证码的真实内容到redis
        redis_conn = get_redis_connection("verify_codes")
        redis_conn.setex("img_%s"% image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES,text)

        #返回给前端
        return HttpResponse(image, content_type='image/jpg')

